package com.qianlou.springai01chat.controller;


import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@Slf4j
@RestController
public class ChatController {

    @Resource
    private OpenAiChatModel openAiChatModel;


    @RequestMapping("/ai/chat")
    public String getChat(@RequestParam("msg") String msg) {
        log.info("您的问题是: {} ", msg);
        String answer = openAiChatModel.call(msg);
        log.info("答案: {}", answer);
        return answer;
    }

    @RequestMapping("/ai/chat2")
    public Object getChat2(@RequestParam("msg") String msg) {
        log.info("您的问题是: {} ", msg);
        Prompt prompt = new Prompt(msg);
        ChatResponse answer = openAiChatModel.call(prompt);
        log.info("答案: {}", answer);
        return answer.getResult().getOutput().getContent();
    }

    @RequestMapping("/ai/chat3")
    public Object getChat3(@RequestParam("msg") String msg) {
        log.info("您的问题是: {} ", msg);
        ChatResponse answer = openAiChatModel.call(new Prompt(msg, OpenAiChatOptions.builder()
                .withModel(OpenAiApi.ChatModel.GPT_4_O)
                .withTemperature(0.2f).build()));
        log.info("答案: {}", answer);
        return answer.getResult().getOutput().getContent();
    }


    @RequestMapping("/ai/chat4")
    public Object getChat4(@RequestParam("msg") String msg) {
        log.info("您的问题是: {} ", msg);
        Flux<String> flux = openAiChatModel.stream(msg);
        log.info("答案: ");
        flux.toStream().forEach(System.out::print);
        return flux.collectList();
    }
}
